#include "suanfa.h"

int bubble_sort(int *arry,int size,int mode){
    int i = 0;
    int j = 0;
    //外循环次数
    for(i=0;i<size-1;i++){
        //内循环次数，每个元素的对比次数，随着外循环次数的减少，成员之间的对比个数也在减少
        for(j=0;j<size-i-1;j++){
            //升序
            if(mode == SORT_ASEC){
                if(arry[j]>arry[j+1]){
                    int temp = arry[j];
                    arry[j] = arry[j+1];
                    arry[j+1] = temp;
                }
            }
            else if(mode == SORT_DESC){
                if(arry[j]<arry[j+1]){
                    int temp = arry[j];
                    arry[j] = arry[j+1];
                    arry[j+1] = temp;
                }
            }
        }
    }
    return 0;
}


int select_sort(int *arry,int size,int mode){
    int i = 0;
    int j = 0;
    int max = 0;
    int min = 0;
    for(i=0;i<size;i++){
        if(mode == SORT_ASEC){
            min = i;
        }
        else if(mode == SORT_DESC){
            max = i;
        }
        for(j=i+1;j<size;j++){
            if(mode == SORT_ASEC){
                if(arry[min]>arry[j]){
                    int temp = arry[min];
                    arry[min] = arry[j];
                    arry[j] = temp; 
                }
            }
            else if(mode == SORT_DESC){
                if(arry[max]<arry[j]){
                    int temp = arry[max];
                    arry[max] = arry[j];
                    arry[j] = temp;
                }
            }
        }
    }    
    return 0;
}

int insert_sort(int *arry,int size,int mode){
    int i = 0;
    int j = 0;
    int key = 0;
    for(i=1;i<size;i++){
        //获取key值
        key = arry[i];
        //获取key值前面的第一个值
        j = i-1;
        if(mode == SORT_ASEC){
            //用key值与key值之前的值进行对比，只要比key值大，就要把值往前移
            while(j>=0 && key<arry[j]){
                arry[j+1] = arry[j];
                j--;
            }
        }
        else if(mode == SORT_DESC){
            //用key值与key值之前的值进行对比，只要比key值小，就要把值往前移
            while(j>=0 && key>arry[j]){
                arry[j+1] = arry[j];
                j--;
            }
        }
        //确定key值目前的位置
        arry[j+1] = key;
    }
    return 0;
}

int show_arry(int *arry,int size){
    int i = 0;
    for(i=0;i<size;i++){
        printf("%d,",arry[i]);
    }
    printf("\n");
    return 0;
}